import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { getSignInTaskDetail, manualSignIn, getSignInTaskStudentDetails, SignInStudentDetail } from '@/services/signIn';
import { SignInTask } from '@/types';
import '../styles/SignInTaskDetail.css';

const SignInTaskDetail: React.FC = () => {
  const { taskId } = useParams<{ taskId: string }>();
  const navigate = useNavigate();
  
  const [task, setTask] = useState<SignInTask | null>(null);
  const [students, setStudents] = useState<SignInStudentDetail[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [processingManualSignIn, setProcessingManualSignIn] = useState(false);
  const [stats, setStats] = useState({
    totalCount: 0,
    signedCount: 0,
    absentCount: 0,
    signInRate: 0
  });

  useEffect(() => {
    fetchTaskData();
  }, [taskId]);

  const fetchTaskData = async () => {
    if (!taskId) return;
    
    try {
      setLoading(true);
      setError(null);
      
      // 获取签到任务详情
      const taskRes = await getSignInTaskDetail(parseInt(taskId));
      if (taskRes.code === 2000 && taskRes.data?.task) {
        setTask(taskRes.data.task);
        
        // 获取学生签到详情
        const studentDetailsRes = await getSignInTaskStudentDetails(parseInt(taskId));
        if (studentDetailsRes.code === 2000) {
          const { students, totalCount, signedCount, absentCount, signInRate } = studentDetailsRes.data || {};
          
          setStudents(students || []);
          setStats({
            totalCount: totalCount || 0,
            signedCount: signedCount || 0,
            absentCount: absentCount || 0,
            signInRate: signInRate || 0
          });
        } else {
          setError(studentDetailsRes.message || '获取学生签到数据失败');
        }
      } else {
        setError(taskRes.message || '获取签到任务详情失败');
      }
    } catch (err: any) {
      setError(err.message || '获取签到任务数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleManualSignIn = async (studentId: string) => {
    if (!taskId || processingManualSignIn) return;
    
    try {
      setProcessingManualSignIn(true);
      setError(null);
      
      const res = await manualSignIn(parseInt(taskId), studentId);
      if (res.code === 2000) {
        setSuccess(`学生 ${studentId} 手动签到成功`);
        
        // 更新状态
        setStudents(prev => 
          prev.map(s => 
            s.student_id === studentId 
              ? { ...s, signStatus: 'signed', signInMethod: 'manual', signInTime: new Date().toISOString() } 
              : s
          )
        );
        
        // 更新统计数据
        setStats(prev => ({
          ...prev,
          signedCount: prev.signedCount + 1,
          absentCount: prev.absentCount - 1,
          signInRate: Math.round(((prev.signedCount + 1) / prev.totalCount) * 100)
        }));
        
        // 3秒后清除成功消息
        setTimeout(() => setSuccess(null), 3000);
      } else {
        setError(res.message || '手动签到失败');
      }
    } catch (err: any) {
      setError(err.message || '手动签到失败');
    } finally {
      setProcessingManualSignIn(false);
    }
  };

  const filteredStudents = searchKeyword 
    ? students.filter(s => 
        s.name.includes(searchKeyword) || 
        s.student_id.includes(searchKeyword)
      )
    : students;
  
  const formatTime = (timeString?: string) => {
    if (!timeString) return '-';
    try {
      const date = new Date(timeString);
      return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
    } catch (e) {
      return timeString;
    }
  };
  
  if (loading) {
    return <div className="loading-container">加载中...</div>;
  }
  
  if (error) {
    return (
      <div className="error-container">
        <div className="error-message">{error}</div>
        <button className="btn btn-primary" onClick={() => navigate(-1)}>返回</button>
      </div>
    );
  }
  
  if (!task) {
    return (
      <div className="error-container">
        <div className="error-message">未找到签到任务</div>
        <button className="btn btn-primary" onClick={() => navigate(-1)}>返回</button>
      </div>
    );
  }

  return (
    <div className="task-detail-container">
      <div className="page-header">
        <button className="btn btn-secondary" onClick={() => navigate(-1)}>
          返回
        </button>
        <h1>签到详情 - {task.course_name}</h1>
      </div>
      
      {/* 签到任务信息卡片 */}
      <div className="task-info-card">
        <div className="card-header">
          <h2>任务 #{task.id} - {task.description || '签到任务'}</h2>
          <span className={`status-badge ${task.status}`}>
            {task.status === 'active' ? '进行中' : '已结束'}
          </span>
        </div>
        
        <div className="task-info-grid">
          <div className="info-item">
            <label>课程:</label>
            <span>{task.course_name}</span>
          </div>
          <div className="info-item">
            <label>班级:</label>
            <span>{task.class_name || '所有班级'}</span>
          </div>
          <div className="info-item">
            <label>开始时间:</label>
            <span>{formatTime(task.start_time)}</span>
          </div>
          <div className="info-item">
            <label>结束时间:</label>
            <span>{formatTime(task.end_time)}</span>
          </div>
          <div className="info-item">
            <label>签到率:</label>
            <span className="sign-in-rate">{stats.signInRate}%</span>
          </div>
        </div>
      </div>
      
      {/* 成功消息 */}
      {success && (
        <div className="success-message">
          {success}
        </div>
      )}
      
      {/* 学生签到列表 */}
      <div className="students-section">
        <div className="section-header">
          <h2>学生签到情况</h2>
          <div className="search-box">
            <input
              type="text"
              placeholder="搜索学生姓名或学号"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
            />
          </div>
        </div>
        
        {students.length === 0 ? (
          <div className="empty-message">暂无学生数据</div>
        ) : (
          <div className="students-table-container">
            <table className="students-table">
              <thead>
                <tr>
                  <th>学号</th>
                  <th>姓名</th>
                  <th>班级</th>
                  <th>签到状态</th>
                  <th>签到时间</th>
                  <th>签到方式</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {filteredStudents.map(student => (
                  <tr 
                    key={student.id} 
                    className={student.signStatus === 'signed' ? 'signed' : student.signStatus === 'absent' ? 'absent' : ''}
                  >
                    <td>{student.student_id}</td>
                    <td>{student.name}</td>
                    <td>{student.class_name || '-'}</td>
                    <td>
                      <span className={`sign-status ${student.signStatus}`}>
                        {student.signStatus === 'signed' ? '已签到' : '未签到'}
                      </span>
                    </td>
                    <td>{formatTime(student.signInTime)}</td>
                    <td>
                      {student.signInMethod === 'face' ? '人脸识别' : 
                       student.signInMethod === 'manual' ? '手动签到' : '-'}
                    </td>
                    <td>
                      {task.status === 'active' && student.signStatus === 'absent' && (
                        <button 
                          className="btn btn-primary btn-sm"
                          disabled={processingManualSignIn}
                          onClick={() => handleManualSignIn(student.student_id)}
                        >
                          {processingManualSignIn ? '处理中...' : '手动签到'}
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        
        <div className="summary-section">
          <div className="summary-item">
            <label>总人数:</label>
            <span>{stats.totalCount}</span>
          </div>
          <div className="summary-item">
            <label>已签到:</label>
            <span className="signed-count">
              {stats.signedCount}
            </span>
          </div>
          <div className="summary-item">
            <label>未签到:</label>
            <span className="absent-count">
              {stats.absentCount}
            </span>
          </div>
          <div className="summary-item">
            <label>签到率:</label>
            <span className="sign-in-rate">{stats.signInRate}%</span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SignInTaskDetail; 